package cn.dengta.webapp.trade.service;

import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.validation.constraints.NotNull;

import cn.dengta.common.model.Status;
import cn.dengta.webapp.base.service.BaseServiceImpl;
import cn.dengta.webapp.trade.dao.UserBagAvatarDao;
import cn.dengta.webapp.trade.entity.UserBagAvatar;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.codeplayer.util.*;
import org.springframework.stereotype.Service;

@Service
public class UserBagAvatarService extends BaseServiceImpl<UserBagAvatar, UserBagAvatarDao, Long> {

	Supplier<Map<String, List<UserBagAvatar>>> bagAvatarLoader;
	private static Map<Long, String> avatar_data = Collections.emptyMap();

	public Map<Long, String> findAvatars() {
		if (X.isValid(avatar_data)) {
			return avatar_data;
		}
		List<UserBagAvatar> list = selectList(null);
		return avatar_data = CollectionUtil.toHashMap(list, UserBagAvatar::getId, UserBagAvatar::getIcon);
	}

	public Map<String, List<UserBagAvatar>> loader(boolean flush) {
		Supplier<Map<String, List<UserBagAvatar>>> loader = bagAvatarLoader;
		if (flush || loader == null) { // 缓存60分钟
			bagAvatarLoader = loader = new TimeBasedCacheLoader<>(EasyDate.MILLIS_OF_HOUR,
					() -> findValid().stream().filter(c -> StringUtil.notEmpty(c.getAlias())).collect(Collectors.groupingBy(UserBagAvatar::getAlias)));
		}
		return loader.get();
	}

	public List<UserBagAvatar> findAliasByCache(boolean flush, @NotNull String alias) {
		if (StringUtil.isEmpty(alias)) {
			return Collections.emptyList();
		}
		List<UserBagAvatar> loader = loader(flush).get(alias);
		return X.isValid(loader) ? new ArrayList<>(loader) : Collections.emptyList();
	}

	public List<UserBagAvatar> findValid() {
		QueryWrapper<UserBagAvatar> wrapper = new QueryWrapper<>();
		wrapper.ge("status", Status.YES.value);
		wrapper.orderByAsc("sort", "id");
		return selectList(wrapper);
	}

}
